﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Xml;
using CamlexNET;
using LifeInSharePoint.Blog.Business.DAL;
using LifeInSharePoint.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace LifeInSharePoint.Blog.Layouts.LifeInSharePoint.Blog
{
    public partial class feed : LayoutsPageBase
    {
        private const string POSTLIST = "Pages";
        private const string CONTENTTYPE = "Life In SharePoint Blog Post";
        private const string RELSITEURL = "/blog";

        protected void Page_Load(object sender, EventArgs e)
        {
            // Clear any previous output from the buffer
            Response.Clear();
            Response.ContentType = "text/xml";
            XmlTextWriter feedWriter
              = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);


            feedWriter.WriteStartDocument();

            // Add processor information to the XML file
            String strPI = "type='text/xsl' href='/_layouts/LifeInSharePoint.Blog/xslt/feed.xsl'";
            // Write processor information
            feedWriter.WriteProcessingInstruction("xml-stylesheet", strPI);

            // These are RSS Tags
            feedWriter.WriteStartElement("rss");
            feedWriter.WriteAttributeString("version", "2.0");
            feedWriter.WriteAttributeString("xmlns:media", "http://search.yahoo.com/mrss/");
            feedWriter.WriteAttributeString("xmlns:atom", "http://www.w3.org/2005/Atom");

            feedWriter.WriteStartElement("channel");
            feedWriter.WriteElementString("title", SPPropertyBagHelper.GetPropertyValue(SPContext.Current.Site.RootWeb, "RSSFeedTitle"));
            feedWriter.WriteElementString("link", SPPropertyBagHelper.GetPropertyValue(SPContext.Current.Site.RootWeb, "RSSFeedLink"));
            feedWriter.WriteElementString("description", SPPropertyBagHelper.GetPropertyValue(SPContext.Current.Site.RootWeb, "RSSFeedDescription"));
            feedWriter.WriteElementString("copyright",SPPropertyBagHelper.GetPropertyValue(SPContext.Current.Site.RootWeb, "RSSFeedCopyright"));

            //GET SHAREPOINT INFO

            //Get the SP Web
            using (SPSite siteCollection = new SPSite(SPContext.Current.Site.RootWeb.Url + RELSITEURL))
            {
                using (SPWeb web = siteCollection.OpenWeb())
                {
                    //Get the List Instance
                    SPList newslist = web.Lists[POSTLIST];

                    //Get a new SPQuery Instance
                    SPQuery workQuery = new SPQuery();

                    //Create Expressions for the CAMLEx
                    var expressions = new List<Expression<Func<SPListItem, bool>>>();
                    expressions.Add(x => ((string) x["ContentType"]) == CONTENTTYPE);
                    var caml = Camlex.Query().WhereAll(expressions).ToString();

                    workQuery.Query = caml + "<OrderBy><FieldRef Name='Modified' Ascending='False'/></OrderBy>";

                    SPListItemCollection _workItemCollection = newslist.GetItems(workQuery);

                    if (_workItemCollection != null && _workItemCollection.Count > 0)
                    {
                        for (int i = 0; i < _workItemCollection.Count; i++)
                        {
                            SPListItem _workItem = _workItemCollection[i];
                            string Title = SPListHelper.GetColumnStringValue(_workItem, "Title");
                            string Excerpt = SPListHelper.GetColumnStringValue(_workItem, "LISPPostExcerpt");
                            DateTime PublishedDate = (DateTime)SPListHelper.GetColumnValue(_workItem, "Modified");
                            string Url = SPListHelper.GetColumnStringValue(_workItem, "EncodedAbsUrl");

                            feedWriter.WriteStartElement("item");
                            feedWriter.WriteElementString("title", Title);
                            feedWriter.WriteElementString("description", Excerpt);
                            feedWriter.WriteElementString("link",Url);
                            feedWriter.WriteElementString("pubDate", FormatPubDate(PublishedDate));
                            feedWriter.WriteEndElement();
                        }
                    }

                }
            }

            //END GET SHAREPOINT INFO

            // Close all open tags tags
            feedWriter.WriteEndElement();
            feedWriter.WriteEndElement();
            feedWriter.WriteEndDocument();
            feedWriter.Flush();
            feedWriter.Close();

            Response.End();
        }

        public static string FormatPubDate(DateTime pubDate)
        {
            string _rfc822Format = "ddd, dd MMM yyyy HH:mm:ss";
            string _tmp = pubDate.ToUniversalTime().ToString(_rfc822Format);

            return _tmp + " UT";

        }

    }
}
